package com.easy.interceptor;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.easy.util.Result;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/*
* 拦截器
* */
public class LoginInterceptor implements HandlerInterceptor {
//管理员也判断String token=request.getHeader(SYS.ADMINISTRATOR);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的token
        String token = request.getHeader("authorization");
        //检查token是否存在且有效
        if(token==null||!TokenUtil.verify( token)){
//            response.setStatus(401);
            Result result=new Result(401,"请先登录",null);
            //hutool
            String json = JSONUtil.toJsonStr(result);
//            //fastjson
//            String jsonString = JSON.toJSONString(result);
            response.getWriter().write(json);
            return false;
        }
        //放行
        return true;
    }





}
